<template>
  <div class="publish">
    <!-- 面包屑模块 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item
        ><a href="javascript:;">文章管理</a></el-breadcrumb-item
      >
      <el-breadcrumb-item>文章列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑模块结束 -->
    <!-- card卡片模块 -->
    <el-card class="box-card">
      <!-- form表单模块 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 标题部分 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <!-- 栏目部分 -->
        <el-form-item label="栏目" prop="categories">
          <!-- 全选 -->
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <!-- 栏目分类 -->
          <el-checkbox-group
            v-model="ruleForm.categories"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              :label="item.id"
              v-for="item in cateList"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <!-- 类型部分 -->
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="ruleForm.type">
            <el-radio label="1">文章</el-radio>
            <el-radio label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 封面部分 -->
        <el-form-item label="封面" prop="title">
          <el-upload
            :action="this.$baseURL + '/upload'"
            list-type="picture-card"
            :on-success="onSuccess"
            :on-remove="onRemove"
            :headers="headers"
            :limit="3"
            :on-exceed="onExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- 内容模块 -->
        <el-form-item label="内容">
          <VueEditor :config="config" ref="vueEditor" />
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交文章</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- form表单模块结束 -->
    </el-card>
    <!-- card卡片模块结束 -->
  </div>
</template>

<script>
import { getCategoryAPI } from "@/apis/category";
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { getToken } from "@/utils/localData";
export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      // 多选按钮
      checkAll: false,
      isIndeterminate: true,
      // 文章详细
      cateList: [],
      // form表单数据
      ruleForm: {
        title: "",
        categories: [],
        type: "1",
        content: "",
        cover: [],
      },
      // 校验规则
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur", //失去焦点时
          },
        ],
        categories: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个栏目",
            trigger: "change",
          },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      // 富文本
      config: {
        // 上传图片的配置
        uploadImage: {
          url: this.$baseURL + "/upload",
          name: "file",
          headers: { Authorization: getToken() },
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess: (res, insert) => {
            // console.log(res);
            if (res.data.message === "文件上传成功") {
              insert(this.$baseURL + res.data.data.url);
            } else {
              this.$message({
                showClose: true,
                message: "文件上传失败",
                duration: 1000,
                type: "error",
              });
            }
          },
        },
        // 上传视频的配置
        // uploadVideo: {
        //   url: "http://localhost:3000/upload",
        //   name: "file",
        //   uploadSuccess(res, insert) {
        //     insert("http://localhost:3000" + res.data.url);
        //   },
        // },
      },
      // 请求头
      headers: { Authorization: getToken() },
      // 封面
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  async created() {
    const res = await getCategoryAPI();
    // console.log(res);
    this.cateList = res.data.data;
    // console.log("cateList", this.cateList);
  },
  methods: {
    // 全选
    handleCheckAllChange(val) {
      // console.log("val", val);.
      this.ruleForm.categories =
        val === true ? this.cateList.map((item) => item.id) : [];
      // console.log("categories", this.ruleForm.categories);
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log("value", value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
    // 提交按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        // console.log("valid", valid);
        // 校验输入的数据都通过校验时
        if (valid) {
          // 如果是文章类型
          if (this.ruleForm.type === "1") {
            this.ruleForm.content = this.$refs.vueEditor.editor.root.innerHTML;
            // console.log("content", this.ruleForm.content);
            // console.log("ruleForm", this.ruleForm);
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 封面
    // 超出图片限制时的钩子
    onExceed() {
      this.$message({
        showClose: true,
        message: "最多上传3个图片封面",
        type: "warning",
      });
    },
    // 文件移除时的钩子
    onRemove(file) {
      // console.log(file, fileList);
      const id = file.response.data.id;
      this.ruleForm.cover = this.ruleForm.cover.filter(
        (item) => item.id !== id
      );
    },
    // 文件上次成功时的钩子
    onSuccess(response) {
      // console.log(response, file, fileList);
      this.ruleForm.cover.push({ id: response.data.id });
      // console.log("cover", this.ruleForm.cover);
    },
  },
};
</script>

<style lang="less" scoped>
.publish {
  .el-breadcrumb {
    margin-bottom: 20px;
  }
}
</style>
